const {BrowserWindow} = require('electron')
const isDev = require('electron-is-dev');
const path = require('path');

const signalTypes = require('../../../signal_types');
const {log} = require("../../../utils/log");
const {
  send: sendMainWindow
} = require('../main')

let win,
  //todo
  controlled_hosts = [];

const create = async (be_controlled_code) => {
  if (!win) {
    win = new BrowserWindow({
      width: 600, //todo 全屏 或则 根据对方屏幕生成？
      height: 300,

      frame: false,
      transparent: true,

      webPreferences: {
        nodeIntegration: true,
        preload: path.join(__dirname, 'preload.js')
      }
    });

    win.on('closed', () => win = null);

    if (isDev) {
      await win.loadURL(process.env.CONTROL_WINDOW_URL);
    }else {
      await win.loadFile(path.resolve(__dirname, '../../../renderer/pages/control/dist/index.html'));
    }
  }

  await send(signalTypes["CONTROL_WINDOW:OPEN_NEW_TAB"], be_controlled_code);

  return win;
}

function send(channel, ...args){
  win.webContents.send(channel, ...args);
}

const close = () => {
  win.close()
};

const minimize = () => {
  win.minimize();
};

const maximize = () => {
  win.maximize();
};

//Restores the window from minimized state to its previous state.
const restore = () => {
  win.restore();
};

const show = () => {
  win.show();
};

module.exports = {
  create,
  send,
  close,
  minimize,
  maximize,
  restore,
  show,
  win
};
